package com.lujianfei.powersearch.widget

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.EditText
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import com.lujianfei.powersearch.R
import com.lujianfei.powersearch.utils.SystemUtils

class SearchBar @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr), TextWatcher {

    var tv_search: TextView? = null
    var edit_search: EditText? = null
    var onSearchBarListener: ((String)->Unit)? = null

    init {
        LayoutInflater.from(context).inflate(R.layout.widget_searchbar, this, true)
        tv_search = findViewById(R.id.tv_search)
        edit_search = findViewById(R.id.edit_search)
        if (null != attrs) {
            val typedArray = context.obtainStyledAttributes(attrs, R.styleable.SearchBar)
            val edit_mode = typedArray.getBoolean(R.styleable.SearchBar_edit_mode, false)
            if (edit_mode) {
                tv_search?.visibility = GONE
                edit_search?.visibility = VISIBLE
            } else {
                tv_search?.visibility = VISIBLE
                edit_search?.visibility = GONE
            }
        }
        edit_search?.addTextChangedListener(this)
    }

    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        if (null != onSearchBarListener) {
            onSearchBarListener?.invoke(edit_search?.text.toString())
        }
    }

    override fun afterTextChanged(s: Editable) {}

    fun showKeyboard() {
        SystemUtils.showInput(edit_search)
    }
}